package com.songqintuan.common.validator;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.log4j.Logger;

import com.songqintuan.common.constant.GlobalConstants;
import com.songqintuan.common.util.MessageFactory;
import com.songqintuan.common.util.Validation;

@SuppressWarnings("serial")
public class UrlValidator implements Validator,Serializable {
	private static Logger logger = Logger.getLogger(Validation.class);
	 /**
	  * 正则验证方法
	  *
	  * @param regexstr
	  * @param str
	  * @return
	  */
	 public static boolean Match(String regexstr, String str) {
	  Pattern regex = Pattern.compile(regexstr,Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
	  Matcher matcher = regex.matcher(str);
	  return matcher.matches();
	 }
	 protected  boolean isEmpty(String s)
	{
		return ((s.equals(null)) || (s.length()==0));
	}
	
	public void validate(FacesContext context, UIComponent component, Object obj)
			throws ValidatorException {
		// TODO Auto-generated method stub
		String webdomainregex = "http://([^/]+)/*";
		
		String url=(String)obj;
		FacesMessage message;
		String label = (String)component.getAttributes().get("label");
		label = (null == label)?"":label;
		if(!isEmpty(url)){
			boolean matchFlag = Match(webdomainregex, url);
			if (!matchFlag)
		 	{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "url.validator.error.message", FacesMessage.SEVERITY_ERROR, label);
		 		throw new ValidatorException(message);
		    }
		}
	}

}

